Skip to content

[3.13] gh-142831: Fix use-after-free in json encoder during re-entrant mutation (gh-142851)#150079

Open
ashm-dev wants to merge 1 commit into
python:3.13from
ashm-dev:backport-gh-142831-3.13
Open

[3.13] gh-142831: Fix use-after-free in json encoder during re-entrant mutation (gh-142851)#150079
ashm-dev wants to merge 1 commit into
python:3.13from
ashm-dev:backport-gh-142831-3.13

Conversation

@ashm-dev
Copy link
Copy Markdown
Contributor

@ashm-dev ashm-dev commented May 19, 2026

Manual backport of #142851 to 3.13 (the bot couldn't cleanly cherry-pick due to refactors in main).

The fix had to be adapted because:

  • In 3.13 the dict/list iteration loops were not yet extracted into the _encoder_iterate_*_lock_held helpers introduced later in main. Added the Py_INCREF/Py_DECREF around each borrowed item/key/value inline in encoder_listencode_dict (both the PyMapping_Items and PyDict_Next paths) and encoder_listencode_list.
  • encoder_encode_key_value in 3.13 has a different signature (no dct parameter, different separator handling).

Only the two UAF regression tests from the original PR were included — test_current_indent_level from the surrounding context is unrelated to this fix and would require additional 3.14-only changes.

Built --with-pydebug and ran ./python -m test test_json -v locally — all 197 tests pass.

… mutation (pythongh-142851)

User callbacks invoked during JSON encoding (e.g. the `default` callback or
a custom string encoder) can mutate or clear the dict or sequence being
encoded, invalidating borrowed references to items, keys, and values. Hold
strong references unconditionally while iterating.

Co-authored-by: Kumar Aditya <kumaraditya@python.org>
Co-authored-by: Gregory P. Smith <greg@krypto.org>
(cherry picked from commit 235fa72)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant